package org.jeecg.modules.wlhy.captain.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.PayConstants;
import org.jeecg.common.constant.enums.ShippingTyeEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.ExcelUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wlhy.captain.entity.HyCaptain;
import org.jeecg.modules.wlhy.captain.entity.ImportHyCaptainDTO;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainService;
import org.jeecg.modules.wlhy.hybank.entity.HyBank;
import org.jeecg.modules.wlhy.hybank.service.IHyBankService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.hyevent.event.PicDownloadEvent;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyDriverVehicle;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyDriverVehicleService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.setting.entity.HySetting;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.HyStatusCheckUtil;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: hy_captain
 * @Author: jeecg-boot
 * @Date:   2024-11-07
 * @Version: V1.0
 */
@Api(tags="hy_captain")
@RestController
@RequestMapping("/hyCaptain")
@Slf4j
public class HyCaptainController extends JeecgController<HyCaptain, IHyCaptainService> {
	@Autowired
	private IHyCaptainService hyCaptainService;

	@Autowired
	private IHyVehicleService hyVehicleService;

	@Autowired
	private ISysUserService	userService;

	@Autowired
	private ISysRoleService roleService;
	@Autowired
	private IHyOrderService hyOrderService;

	@Autowired
	private IHyDriverService hyDriverService;
	@Autowired
	private IHySettingService settingService;
	@Autowired
	private IHyShippingNoteService hyShippingNoteService;
	@Autowired
	private IHyDriverVehicleService hyDriverVehicleService;
	@Autowired
	private IHyDriverBankService hyDriverBankService;

	@Autowired
	private UserUtil userUtil;

    @Autowired
    private IHyBankService bankService;
	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;

	@Autowired
	private ApplicationEventPublisher applicationEventPublisher;

	
	/**
	 * 分页列表查询
	 *
	 * @param hyCaptain
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="hy_captain-分页列表查询", notes="hy_captain-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HyCaptain hyCaptain,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HyCaptain> queryWrapper = QueryGenerator.initQueryWrapper(hyCaptain, req.getParameterMap());
		Page<HyCaptain> page = new Page<HyCaptain>(pageNo, pageSize);
		IPage<HyCaptain> pageList = hyCaptainService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param hyCaptain
	 * @return
	 */
	@AutoLog(value = "hy_captain-添加")
	@ApiOperation(value="hy_captain-添加", notes="hy_captain-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody HyCaptain hyCaptain) {

		//查询是否存在该手机号
		HyCaptain captain = hyCaptainService.getOne(new QueryWrapper<HyCaptain>().eq("login_phone",hyCaptain.getLoginPhone()).eq("del_flag","0"));
		if (captain != null) {
			return Result.error("该手机号已存在");
		}
		saveThat(hyCaptain);
		HyBank bank = bankService.getByBankType(hyCaptain.getBankType());
		if (bank!=null){
			hyCaptain.setCrBankNo(bank.getBankHh());
		}else {
			return Result.error("该银行行号信息缺失,请联系管理员进行添加");
		}
		checkInfo(hyCaptain);
		hyCaptainService.save(hyCaptain);
		return Result.OK("添加成功！");
	}

	private void checkInfo(HyCaptain hyCaptain) {
		if (StringUtils.isEmpty(hyCaptain.getCaptainName())){
			throw new JeecgBootException("承运商名称不能为空");
		}
		if (StringUtils.isEmpty(hyCaptain.getLoginPhone())){
			throw new JeecgBootException("登录手机号不能为空");
		}
		if (StringUtils.isEmpty(hyCaptain.getBankType())){
			throw new JeecgBootException("开户银行不能为空");
		}
		if (StringUtils.isEmpty(hyCaptain.getBankName())){
			throw new JeecgBootException("开户人名称不能为空");
		}
		if (StringUtils.isEmpty(hyCaptain.getBankNum())){
			throw new JeecgBootException("开户人银行卡号不能为空");
		}
		if (StringUtils.isEmpty(hyCaptain.getKhTel())){
			throw new JeecgBootException("开户人电话不能为空");
		}
		if (StringUtils.isEmpty(hyCaptain.getIdcard())){
			throw new JeecgBootException("开户人身份证号不能为空");
		}
	}

	private void saveThat(HyCaptain captain) {
		SysUser suser = userService.getUserByPhone(captain.getLoginPhone());
		String name = "承运商";
		String carrierRoleID = roleService.getRoleByName(name);
		if(suser == null){
			//添加登陆账号
			SysUser user = new SysUser();
//          String username = loginPhone;//设置登陆账号为手机号
			String username = userService.createRandomUserName();//随机生成账号
			user.setUType("7");
			user.setUsername(username);
			user.setRealname(captain.getCaptainName());
			user.setPhone(captain.getLoginPhone());
			user.setCreateTime(new Date());//设置创建时间
			String salt = oConvertUtils.randomGen(8);
			user.setSalt(salt);
			user.setPassword("Aa.123456");//设置默认密码123456
			String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
			user.setPassword(passwordEncode);
			user.setStatus(1);
			user.setDelFlag(CommonConstant.DEL_FLAG_0);
			userService.addUserWithRole(user, carrierRoleID);
			captain.setUserId(user.getId());
			captain.setUserName(username);

		}else {
			if (!suser.getRealname().equals(captain.getCaptainName())){
				throw new JeecgBootException("用户姓名与承运商姓名不一致");
			}
			//补充承运商和角色信息
			suser.setUType("7");
			captain.setUserId(suser.getId());
			captain.setUserName(suser.getUsername());
			captain.setIzUsed("1");
			//获取用户的角色列表
			List<SysUserRole> userRoles = userService.getUserRoles(suser.getId());
			List<String> roleIds = userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());

			String roles = "";
			for (String roleId : roleIds) {
				roles += roleId + ",";
			}
			if (!roleIds.contains(carrierRoleID)){
				roles+=carrierRoleID;
			}
			userService.editUserWithRole(suser, roles);
		}

	}
	
	/**
	 *  编辑
	 *
	 * @param hyCaptain
	 * @return
	 */
	@AutoLog(value = "hy_captain-编辑")
	@ApiOperation(value="hy_captain-编辑", notes="hy_captain-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody HyCaptain hyCaptain) {
		hyCaptainService.updateById(hyCaptain);
		/*if (!hyCaptain.getCaptainName().equals(hyCaptain.getBankName())){
			return Result.error("承运商名称与绑定银行卡户主名称不一致");
		}*/
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "hy_captain-通过id删除")
	@ApiOperation(value="hy_captain-通过id删除", notes="hy_captain-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {

		HyCaptain captain = hyCaptainService.getById(id);
		if (captain == null) {
			return Result.error("未找到对应数据");
		}
		try {
			int count = hyCaptainService.deleteById(id);
			if (count == 0) {
				return Result.error("删除失败");
			}
		}catch (Exception e){
			log.error("删除失败", e.getMessage());
			return Result.error("删除失败");
		}
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "hy_captain-批量删除")
	@ApiOperation(value="hy_captain-批量删除", notes="hy_captain-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> list = Arrays.asList(ids.split(","));
		for (int i = 0; i < list.size(); i++) {
			String id =	list.get(i);
			int count = hyCaptainService.deleteById(id);
			if (count == 0) {
				return Result.error("删除失败");
			}
		}
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="hy_captain-通过id查询", notes="hy_captain-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		HyCaptain hyCaptain = hyCaptainService.getById(id);
		if(hyCaptain==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hyCaptain);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hyCaptain
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HyCaptain hyCaptain) {
        return super.exportXls(request, hyCaptain, HyCaptain.class, "hy_captain");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HyCaptain.class);
    }
	/**
	 * 根据车队长id获取绑定车辆列表
	 */
	@AutoLog(value = "根据车队长id获取绑定车辆列表")
	@GetMapping(value = "/getVehicleListByHyCaptainId")
	public Result<?> getVehicleListByHyCaptainId(@RequestParam(name = "HyCaptainId") String hyCaptainId) {
		return Result.OK(hyVehicleService.getVehicleListByHyCaptainId(hyCaptainId));
	}
	/**
	 * 指派承运商
	 */
	@AutoLog(value = "指派承运商")
	@PutMapping(value = "/binding")
	public Result<?> binding(@RequestBody JSONObject jsonObject) {
		String orderId = jsonObject.getString("orderId");
		String captainId = jsonObject.getString("captionId");
		String carrierFeeType = jsonObject.getString("shippingType");
		String carrierUnitFee = jsonObject.getString("shippingUnitPrice");
		Result result = hyCaptainService.checkData(orderId,captainId,carrierFeeType,carrierUnitFee);
		if (!result.isSuccess()){
			return result;
		}
		return Result.OK(hyCaptainService.binding(orderId,captainId,carrierFeeType,carrierUnitFee));
	}
	/**
	 * 派单
	 */
	@AutoLog(value = "运单表-派单")
	@ApiOperation(value = "运单表-派单", notes = "运单表-派单")
	@PutMapping(value = "/paidan")
//	@RequiresPermissions("shipping:paidan")
	public Result<?> paidan(@RequestBody JSONObject jsonObject) {

		String orderId = jsonObject.getString("orderId");
		String vehicleId = jsonObject.getString("vehicleId");
		String driverId = jsonObject.getString("driverId");
		String shippingType = jsonObject.getString("shippingType");
		String strshippingUnitPrice = jsonObject.getString("shippingUnitPrice");
		String carrierUnitFee = jsonObject.getString("carrierUnitFee");
		HyOrder order = hyOrderService.getById(orderId);
		if (StringUtils.isEmpty(shippingType)){
			shippingType=order.getShippingType();
		}
		if (StringUtils.isEmpty(strshippingUnitPrice)){
			strshippingUnitPrice=order.getShippingUnitPrice().toString();
		}
		HyStatusCheckUtil.checkShippingType(shippingType);
		BigDecimal shippingUnitPrice = new BigDecimal(strshippingUnitPrice);

		if (!shippingType.equals(order.getShippingType())){
			return Result.error("运费计算方式与货源不一致，请重新选择");
		}

		//代收人模式
		if (shippingType.equals(ShippingTyeEnum.SHIPPING_TYE_1.getCode())&&order.getPayType().equals(PayConstants.PAY_TYPE.BY_CARRIER)&&shippingUnitPrice.compareTo(order.getCarrierUnitFee())<0){
			return Result.error("运费单价不能小于代收人运费单价");
		}
		if (shippingType.equals(ShippingTyeEnum.SHIPPING_TYE_4.getCode())&&order.getPayType().equals(PayConstants.PAY_TYPE.BY_CARRIER)&&shippingUnitPrice.compareTo(order.getCarrierUnitFee())<0){
			return Result.error("运费不能小于代收人运费");
		}
		//预付模式
		if (shippingType.equals(ShippingTyeEnum.SHIPPING_TYE_1.getCode())&&order.getPayType().equals(PayConstants.PAY_TYPE.BY_PREPAY)&&shippingUnitPrice.compareTo(order.getPreUnitFee())<0){
			return Result.error("运费单价不能小于预付运费单价");
		}
		if (shippingType.equals(ShippingTyeEnum.SHIPPING_TYE_4.getCode())&&order.getPayType().equals(PayConstants.PAY_TYPE.BY_PREPAY)&&shippingUnitPrice.compareTo(order.getPreUnitFee())<0){
			return Result.error("运费不能小于预付运费");
		}


		order.setShippingUnitPrice(shippingUnitPrice);
		order.setShippingType(shippingType);

		if (StringUtils.isEmpty(orderId)) {
			return Result.error("货源信息不能为空");
		}
		if (StringUtils.isEmpty(driverId)) {
			return Result.error("司机信息不能为空");
		}
		if (StringUtils.isEmpty(vehicleId)) {
			return Result.error("车辆信息不能为空");
		}
		if (StringUtils.isEmpty(carrierUnitFee)) {
			return Result.error("承运商运费信息不能为空");
		}
		if (shippingType.equals(ShippingTyeEnum.SHIPPING_TYE_1.getCode())&&shippingUnitPrice.compareTo(order.getCarrierUnitFee())<0){
			return Result.error("运费单价不能小于承运商运费单价");
		}
		if (shippingType.equals(ShippingTyeEnum.SHIPPING_TYE_4.getCode())&&shippingUnitPrice.compareTo(order.getCarrierUnitFee())<0){
			return Result.error("运费不能小于承运商运费");
		}

		if (order == null) {
			return Result.error("货源信息不存在");
		}


		if ("8".equals(order.getOrderStatus())) {
			return Result.error("该货源已完结,不能接单");
		}
		if (!"2".equals(order.getOrderStatus())) {
			return Result.error("该货源未发布,不能接单");
		}

		String izUsedGas = jsonObject.getString("izUsedGas");
		String gasRechargeAmount = jsonObject.getString("gasRechargeAmount");
		if (izUsedGas != null) {
			if (!"0".equals(izUsedGas)) {
				if (StringUtils.isEmpty(gasRechargeAmount)) {
					return Result.error("充值金额不能为空");
				} else {
					order.setGasRechargeAmount(new BigDecimal(gasRechargeAmount));
				}
			}
			order.setIzUsedGas(izUsedGas);
		}

		/*if (!userUtil.isSys()) {
			SysUser user = userUtil.getUser();
			if (!"5".equals(user.getUType())) {
				HyCustomer customer = userUtil.getCustomer();
				if (customer == null) {
					return Result.error("货主信息不存在!");
				}
				//司机 货主添加关系表
				hyDriverCustomerService.addDriverCustomer(driverId, customer.getId());
				hyDriverCustomerService.addVehicleCustomer(vehicleId, customer.getId());
				if ("3".equals(order.getOrderMode())) {
					if (!StringUtils.equals(order.getAgentId(), customer.getId())
							&& !StringUtils.equals(order.getCustomerId(), customer.getId())
					) {
						return Result.error("货源信息错误!");
					}
				} else {
					if (!StringUtils.equals(order.getCustomerId(), customer.getId())) {
						return Result.error("货源信息错误!");
					}
				}
			}

		}*/


		HyDriver driver = hyDriverService.getById(driverId);
		if (driver == null) {
			return Result.error("司机信息不存在");
		}

		HySetting hySetting = settingService.getByTag("checkValidDriver");
		if (hySetting!=null&&hySetting.getData().equals("1")){
			Result result = hyDriverService.checkValidDriver(driver);
			if (result.getCode() == 500) {
				return Result.error(result.getMessage());
			}
		}


		HyVehicle vehicle = hyVehicleService.getById(vehicleId);
		if (vehicle == null) {
			return Result.error("车辆信息不存在");
		}
		if (!"2".equals(vehicle.getExamineStatus())) {
			return Result.error("车辆信息未通过审核");
		}
		if ("0".equals(vehicle.getIzUsed())){
			return Result.error("选择的车辆未启用，请重新选择");
		}
		//检查车辆是否是司机的
		HyDriverVehicle driverVehicle = hyDriverVehicleService.getInfoByDriverIdAndVehicleId(driverId, vehicleId);
		if (driverVehicle == null) {
			return Result.error("所选车辆不属于司机");
		}
		//查找司机默认银行卡
		HyDriverBank defaultDriverBank = hyDriverBankService.getDefaultDriverBank(driverId);
		String driverBankId = "";
		if (defaultDriverBank != null) {
			driverBankId = defaultDriverBank.getId();
		}
		Result r = hyShippingNoteService.addByOrder(order, driver, vehicle, null, "", "", driverBankId);
		if (r.getCode() == 500) {
			return Result.error(r.getMessage());
		}
		HyShippingNote hyShippingNote = (HyShippingNote) r.getResult();
		//如果角色是承运商的话
		if (userUtil.isCaptain()){
			//添加运单和承运商关联
			HyCaptain captain = hyCaptainService.getInfoByUserId(userUtil.getLoginUser().getId());
			hyShippingNote.setCaptainId(captain.getId());
			hyShippingNote.setCaptainFeeType(shippingType);
			hyShippingNote.setCaptainUnitFee(new BigDecimal(carrierUnitFee));
			hyShippingNote.setIzCaptainShipping("1");
			hyShippingNoteService.updateById(hyShippingNote);
		}
		return r;
	}
	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/importHyCaptain", method = RequestMethod.POST)
	@Transactional(rollbackFor = Exception.class)
	public Result<?> ImportHyCaptain(HttpServletRequest request) throws InterruptedException {
		List<ImportHyCaptainDTO> list1 = ExcelUtil.importExcel(request, ImportHyCaptainDTO.class);
		List<ImportHyCaptainDTO> list = list1.stream().filter(item -> item.getCaptainName() != null).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(list)) {
			return Result.error("导入数据不能为空！");
		}
		this.checkData(list);
		//登录手机号是否存在
		List<String> captainTelList = list.stream().map(
				item -> item.getLoginPhone().trim()
		).distinct().filter(Objects::nonNull).collect(Collectors.toList());
		int section = 10;
		List<HyCaptain> captainList = new LinkedList<>();
		for (int index = 0, end = 0; index < captainTelList.size(); index = end) {
			end = (end + section) <= captainTelList.size() ? end + section : captainTelList.size();
			if (index < end) {
				QueryWrapper<HyCaptain> queryCaptainWrapper = new QueryWrapper();
				queryCaptainWrapper.in("login_phone", captainTelList.subList(index, end));
				captainList.addAll(hyCaptainService.list(queryCaptainWrapper));
			}
		}
		if (captainList.size() > 0) {

			List<String> dbLoginPhones = captainList.stream().map(
					item -> item.getLoginPhone()
			).collect(Collectors.toList());

			String filterLoginPhones = captainTelList.stream()
					.filter(item -> dbLoginPhones.contains(item))
					.collect(Collectors.joining(",", "(", ")"));
			//return Result.error("登录手机号"+filterLoginPhones + "承运商数据信息已存在");
			log.error("登录手机号{}承运商数据信息已存在", filterLoginPhones);
			//list列表添加迭代器删除已存在的信息
			Iterator<ImportHyCaptainDTO> iterator = list.iterator();
			while (iterator.hasNext()) {
				ImportHyCaptainDTO dto = iterator.next();
				//如果登录手机号存在
				if (captainList.stream().anyMatch(item -> item.getLoginPhone().equals(dto.getLoginPhone()))) {
					iterator.remove();
				}
			}
		}
		//根据图片URL下载图片
		int index = 0;
		for (ImportHyCaptainDTO dto : list) {
			String serverFolderPath = this.uploadpath + File.separator + "captain";
			//证件照正面
			if (StrUtil.isNotEmpty(dto.getIdcardImg())) {
				String idcardImgPath = postDownloadEvent(dto.getIdcardImg(), serverFolderPath, dto.getCaptainName());
				//覆盖导入的长地址，启用网货平台对应的短地址,前面拼接driver目录
				dto.setIdcardImg("captain/" + idcardImgPath);
				Thread.sleep(300);
			}
			//证件照反面
			if (StrUtil.isNotEmpty(dto.getIdcardImgBack())) {
				String idcardImgBackPath = postDownloadEvent(dto.getIdcardImgBack(), serverFolderPath, dto.getCaptainName());
				dto.setIdcardImgBack("captain/" + idcardImgBackPath);
			}
			//银行卡正面
			if (StrUtil.isNotEmpty(dto.getBankImgFront())) {
				String bankImgFrontPath = postDownloadEvent(dto.getBankImgFront(), serverFolderPath, dto.getBankName());
				dto.setIdcardImgBack("captain/" + bankImgFrontPath);
			}
			//银行卡类型及行号
			HyBank bank = bankService.getByBankName(dto.getBankType());
			if (bank!=null){
				dto.setCrBankNo(bank.getBankHh());
				dto.setBankType(bank.getBankType());
			}else {
				log.error("登录手机号为 {} 开户行信息缺失,请联系管理员进行添加", dto.getLoginPhone());
				continue;
			}
			log.info("正在下载{}图片 {}/{}", dto.getCaptainName(), index, list.size());
			index++;
		}
		hyCaptainService.saveBatchCaptain(list);
		return Result.OK("文件导入成功！数据行数：" + list.size());
	}
	private void checkData(List<ImportHyCaptainDTO> list) {
		int i = 1;
		for (ImportHyCaptainDTO importHyCaptainDTO : list) {
			String key = String.valueOf(i);
			if (StringUtils.isBlank(importHyCaptainDTO.getCaptainName())) {
				throw new JeecgBootException("第" + key + "行承运商名称不能为空,请先补充信息");
			}
			if (StringUtils.isBlank(importHyCaptainDTO.getLoginPhone())) {
				throw new JeecgBootException("第" + key + "行身登录手机号不能为空,请先补充信息");
			}
			if (StringUtils.isBlank(importHyCaptainDTO.getBankType())) {
				throw new JeecgBootException("第" + key + "行开户行名称不能为空,请先补充信息");
			}
			if (StringUtils.isBlank(importHyCaptainDTO.getBankName())) {
				throw new JeecgBootException("第" + key + "行开户人姓名不能为空,请先补充信息");
			}
			if (StringUtils.isBlank(importHyCaptainDTO.getBankNum())) {
				throw new JeecgBootException("第" + key + "行开户人银行卡号不能为空,请先补充信息");
			}
			if (StringUtils.isBlank(importHyCaptainDTO.getKhTel())) {
				throw new JeecgBootException("第" + key + "行开户人手机号码不能为空,请先补充信息");
			}
			if (StringUtils.isBlank(importHyCaptainDTO.getIdcard())) {
				throw new JeecgBootException("第" + key + "行开户人身份证号不能为空,请先补充信息");
			}
			SysUser user = userService.getUserByPhone(importHyCaptainDTO.getLoginPhone());
			if (user != null) {
				throw new JeecgBootException("第" + key + "行登录手机号已存在,请更换手机号");
			}
			i++;
		}
	}
	private String postDownloadEvent(String downloadUrl, String serverFolderPath, String serverFolderName) {

		this.applicationEventPublisher.publishEvent(PicDownloadEvent.builder()
				.type("captain")
				.downloadUrl(downloadUrl)
				.serverFolderPath(serverFolderPath)
				.serverFolderName(serverFolderName)
				.build()
		);

		int lastIndex = downloadUrl.lastIndexOf('/');
		String filename = downloadUrl.substring(lastIndex);
		return serverFolderName + File.separator + filename;
	}
}
